package xiaoqianlang.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.View;
import xiaoqianlang.mapper.UserMapper;
import xiaoqianlang.pojo.User;
import xiaoqianlang.service.UserService;
import xiaoqianlang.util.PasswordUtil;

/**
 * @Author：xiaoqianlang
 * @Package：xiaoqianlang.service.impl
 * @Project：PasswordManage
 * @name：UserServiceImpl
 * @Date：2025/4/3/周四 14:38
 * @Filename：UserServiceImpl
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private View error;

    //用户注册
    @Transactional
    public void register(String username,String email,String rawPassword){
        //检查用户名是否存在
        if (userMapper.findByUsername(username) != null){
            throw new RuntimeException("用户名已存在!");
        }
        //检查邮箱是否存在
        if (userMapper.findByEmail(email) != null){
            throw new RuntimeException("邮箱已被注册!");
        }
        //加强密码
        String encodePassword = PasswordUtil.encodePassword(rawPassword);
        //创建用户对象
        User user =new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword_hash(encodePassword);
        user.setSalt(""); //如果使用BCrypt，盐值已包含在加密结果中
        //插入数据库
        userMapper.insertUser(user);
    }
    //用户登录
    public User login(String usernameOrEmail,String rawPassword){
        //查找用户（支持用户名和邮箱登录)
        User user = userMapper.findByUsername(usernameOrEmail);
        if (user == null) {
            user = userMapper.findByEmail(usernameOrEmail); //如果用户名不存在，尝试用邮箱查找
        }
        if (user == null){
            throw new RuntimeException("用户名或邮箱不存在！");
        }
        //验证密码
        if (!PasswordUtil.verifyPassword(rawPassword,user.getPassword_hash())){
            throw new RuntimeException("密码错误！");
        }
        return user;
    }
    //用户信息查询{id username email)
    public User getUserById(Long userid){
        User user = userMapper.findById(userid);
        if (user == null){
            throw new RuntimeException("用户不存在!");
        }
        return user;
    }
    public User getUserByUsername(String username){
        User user = userMapper.findByUsername(username);
        if (user == null){
            throw new RuntimeException("用户名不存在！");
        }
        return user;
    }
    public User getUserByEmail(String email){
        User user = userMapper.findByEmail(email);
        if (user == null){
            throw new RuntimeException("邮箱不存在！");
        }
        return user;
    }

}
